import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../entity/news_entity.dart';
import '../entity/user_entity.dart';
import '../util/dio_util.dart';
import '../util/my_colors.dart';
import '../custom_widget/my_drawer.dart';
import '../custom_widget/my_leading.dart';

import '../custom_widget/news_swiper.dart';
import '../custom_widget/news_list_item.dart';

class NewsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return _PageBody();
  }
}

class _PageBody extends StatefulWidget {
  @override
  __PageBodyState createState() => __PageBodyState();
}

class __PageBodyState extends State<_PageBody>
    with SingleTickerProviderStateMixin {
  List<NewsData> _newsDatas;
  List<UserData> _userDatas;
  TextStyle _tabStyle = TextStyle(fontSize: 17, color: Colors.black);
  TabController _tabController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _appBar(context),
      body: TabBarView(
        children: <Widget>[
          FutureBuilder(future: _initData(), builder: _BuilderFuture),
          FutureBuilder(future: _initData(), builder: _BuilderFuture),
          FutureBuilder(future: _initData(), builder: _BuilderFuture)
        ],
        controller: _tabController,
      ),
      drawer: MyDrawer(),
    );
  }

  AppBar _appBar(BuildContext context) {
    return AppBar(
      leading: MyLeading(),
      title: Text(
        "资讯",
        style: _tabStyle,
      ),
      bottom: TabBar(
        tabs: <Widget>[
          Text("全部", style: _tabStyle),
          Text("推荐", style: _tabStyle),
          Text("关注", style: _tabStyle)
        ],
        controller: _tabController,
        isScrollable: true,
      ),
      actions: <Widget>[
        IconButton(
          icon: Icon(
            Icons.search,
            color: Colors.blue,
            size: 25,
          ),
          onPressed: () {},
        )
      ],
    );
  }

  @override
  void initState() {
    _tabController = new TabController(length: 3, vsync: this);
  }

  Widget _BuilderFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.waiting:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        return _List();
      case ConnectionState.none:
        return Center(
          child: GestureDetector(
            child: Text(
              "加载失败，点击这里重试",
              style: TextStyle(fontSize: 30),
            ),
            onTap: () {
              setState(() {});
            },
          ),
        );
    }
  }

  Future _initData() async {
    print("_initData():================");
    //获取全部资讯
    var response = await DioUtil().sendPostReq("news/getAll", null);
    NewsEntity newsEntity = NewsEntity().fromJson(response.data);
    //初始化资讯数组
    _newsDatas = newsEntity.data;
    //初始化用户数组

    List<UserData> temp = new List();
    //根据资讯中的用户id查询用户并存储在_userDatas中
    for (int i = 0; i < _newsDatas.length; i++) {
      var userRes = await DioUtil()
          .sendPostReq("user/findOne", {"id": _newsDatas[i].userId});
      ;
      temp.add(UserEntity().fromJson(userRes.data).data);
    }

    _userDatas = temp;
  }

  Widget _List() {
    return Container(
      height: double.infinity,
      width: double.infinity,
      color: MyColors.mainColor,
      child: ListView.builder(
        shrinkWrap: true,
        itemCount: _newsDatas.length + 1,
        itemBuilder: (context, index) {
          //return NewsListItem(_newsDatas,_userDatas,index);
          if (index != 0) {
            return new NewsListItem(_newsDatas, _userDatas, index - 1);
          } else {
            return NewsSwiper();
          }
        },
      ),
    );
  }
}
